package com.lekang.framework.web.service;

import javax.annotation.Resource;

import com.lekang.common.core.domain.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import com.lekang.common.constant.CacheConstants;
import com.lekang.common.constant.Constants;
import com.lekang.common.constant.UserConstants;
import com.lekang.common.core.domain.model.LoginUser;
import com.lekang.common.core.redis.RedisCache;
import com.lekang.common.exception.ServiceException;
import com.lekang.common.exception.user.BlackListException;
import com.lekang.common.exception.user.CaptchaException;
import com.lekang.common.exception.user.CaptchaExpireException;
import com.lekang.common.exception.user.UserNotExistsException;
import com.lekang.common.exception.user.UserPasswordNotMatchException;
import com.lekang.common.utils.DateUtils;
import com.lekang.common.utils.MessageUtils;
import com.lekang.common.utils.StringUtils;
import com.lekang.common.utils.ip.IpUtils;
import com.lekang.framework.manager.AsyncManager;
import com.lekang.framework.manager.factory.AsyncFactory;
import com.lekang.framework.security.context.AuthenticationContextHolder;
import com.lekang.system.service.ISysConfigService;
import com.lekang.system.service.ISysUserService;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            redisCache.deleteObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        userService.updateLoginInfo(userId, IpUtils.getIpAddr(), DateUtils.getNowDate());
    }

    public String wxlogin(String phone) {
        // 登录前置校验
        // 用户验证
        SysUser existingUser = userService.selectUserByUserName(phone);
        // 2. 如果用户不存在，则自动注册
        if (existingUser == null) {
            // 创建新用户对象
            SysUser newUser = new SysUser();
            // 给当前新注册的用户设置角色id
            newUser.setRoleIds(new Long[]{100L});
            newUser.setDeptId(100L);
            newUser.setUserName(phone); // 用户名设为手机号
            newUser.setPhonenumber(phone); // 手机号字段
            newUser.setNickName("微信用户" + phone.substring(7)); // 设置一个默认昵称
            newUser.setStatus("0"); // 用户状态：0-正常

            // 设置默认密码（重要：必须加密！）
            String defaultPassword = "123456";
            newUser.setPassword(passwordEncoder.encode(defaultPassword));

            // 你可以根据业务需求设置其他默认值，例如角色ID
            // newUser.setRoleIds(new Long[]{100L}); // 假设100是普通用户的角色ID

            // 调用Service层方法插入新用户
            userService.insertUser(newUser);

            // 插入后，`newUser`对象的主键（userId）会被数据库自动回填
            System.out.println("新用户注册成功，ID: " + newUser.getUserId());
        }


        Authentication authentication = null;
        String password="123456";
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(phone,password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public String wxPhoneLogin(String phone) {
        Authentication authentication = null;
        String password="123456";
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(phone,password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    // 验证码Redis键前缀（需与发送验证码时的键一致）
    private static final String VERIFY_CODE_KEY_PREFIX = "email:verify:";

    // 自动注册默认密码（与wxlogin保持一致）
    private static final String DEFAULT_PASSWORD = "123456";
    public String emaillogin(String email,String emailCode) {
        // 一、验证码前置校验
        if (StringUtils.isAnyBlank(email, emailCode)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(email, Constants.LOGIN_FAIL, "邮箱和验证码不能为空"));
            throw new ServiceException("邮箱和验证码不能为空");
        }

        // 从Redis获取存储的验证码（并删除，防止重复使用）
        String redisKey = VERIFY_CODE_KEY_PREFIX + email;
        String storedCode = stringRedisTemplate.opsForValue().get(redisKey);


        // 验证码过期校验
        if (StringUtils.isBlank(storedCode)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(email, Constants.LOGIN_FAIL, "验证码已过期"));
            throw new ServiceException("验证码已过期，请重新获取");
        }

        // 验证码正确性校验
        if (!storedCode.equals(emailCode)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(email, Constants.LOGIN_FAIL, "验证码错误"));
            throw new ServiceException("验证码错误，请重新输入");
        }
        redisCache.deleteObject(redisKey);


        // 二、用户验证与自动注册（参考wxlogin逻辑）
        SysUser existingUser = userService.selectUserByEmail(email);

        // 若用户不存在，自动注册
        if (existingUser == null) {
            SysUser newUser = new SysUser();
            newUser.setRoleIds(new Long[]{100L}); // 与wxlogin一致的角色ID
            newUser.setDeptId(100L); // 与wxlogin一致的部门ID
            newUser.setUserName(email); // 用户名设为邮箱
            newUser.setEmail(email); // 邮箱字段
            newUser.setPhonenumber(""); // 手机号为空（可按需调整）
           // newUser.setNickName("邮箱用户" + email.substring(email.indexOf("@"))); // 默认昵称
            // 处理邮箱，生成“后四位 + @域名”格式的默认昵称
            // 生成默认昵称：邮箱用户 + @前的后四位 + @及后面的域名
            int atIndex = email.indexOf("@");
            if (atIndex > 0) {
                String prefixPart;
                if (atIndex >= 4) {
                    // @前长度 >=4，截取后四位
                    prefixPart = email.substring(atIndex - 4, atIndex);
                } else {
                    // @前长度 <4，截取全部前缀
                    prefixPart = email.substring(0, atIndex);
                }
                // 拼接成“邮箱用户 + 后四位 + @域名”格式
                String nickName = "邮箱用户" + prefixPart + email.substring(atIndex);
                newUser.setNickName(nickName);
            } else {
                // 极端情况：邮箱无@符号（理论上不会，因为前置校验过邮箱格式）
                newUser.setNickName("邮箱用户");
            }
            newUser.setStatus("0"); // 正常状态
            newUser.setPassword(passwordEncoder.encode(DEFAULT_PASSWORD)); // 密码加密存储

            // 插入新用户
            userService.insertUser(newUser);
            // 重新查询用户信息（确保后续认证可用）
            existingUser = userService.selectUserByEmail(email);
        }


        // 三、Spring Security认证（复用wxlogin的认证逻辑）
        Authentication authentication = null;
        try {
            // 构造认证令牌（用户名=邮箱，密码=默认密码）
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(email, DEFAULT_PASSWORD);
            AuthenticationContextHolder.setContext(authenticationToken);

            // 执行认证（触发UserDetailsServiceImpl.loadUserByUsername）
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            // 认证失败处理
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(email, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(email, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }


        // 四、认证成功处理
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(email, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        // 复用已有的登录信息记录方法（更新IP和时间）
        recordLoginInfo(loginUser.getUserId());

        // 五、生成JWT令牌
        return tokenService.createToken(loginUser);
    }
}
